//不同版本的依赖包用法不一定相同，不一定适合同一版本的webpack
const { resolve } = require("path");
let htmlwebpackplugin = require('html-webpack-plugin')
let MiniCssExtractPlugin = require('mini-css-extract-plugin') //分离css
let OpitimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin') //压缩css]
let WorkboxWebpackPlugin = require('workbox-webpack-plugin')
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
let CopyWebpackPlugin = require('copy-webpack-plugin')
let WebPack = require('webpack')
module.exports = (env, argv) => {
    console.log(env, argv)
    return {
        entry: './src/index.js',
        output: {
            filename: '[name].[contenthash:10].js',
            path: resolve(__dirname, 'build')
        },
        module: {
            rules: [
                {
                    test: /\.js$/i,
                    loader: 'eslint-loader',
                    //优先执行
                    enforce: 'pre',
                    exclude: /(node_modules|dll)/,
                    options: {
                        //自动修复语法错误
                        fix: true,
                        "plugins": [
                            "syntax-dynamic-import"
                        ]
                    }
                },
                {
                    oneOf: [
                        {
                            test: /\.css$/,
                            use: [MiniCssExtractPlugin.loader,
                                'css-loader',
                            {
                                loader: 'postcss-loader',
                                options: {
                                    postcssOptions: {
                                        plugins: [
                                            [
                                                'postcss-preset-env'
                                            ]
                                        ]
                                    }
                                }
                            }

                            ]
                        },
                        {
                            test: /\.(jpg|png)$/,
                            loader: 'url-loader',
                            options: {
                                limit: 8 * 1024,
                                esModule: false,
                                name: '[hash:10].[ext]',
                                outputPath: 'img',
                                publicPath: '../img'
                            }
                        },
                        {
                            test: /\.js$/i,
                            exclude: /(node_modules|dll)/,
                            use: [
                                // {
                                // 	/**多进程打包，提高打包速度，
                                // 	   但是进程启动需要600ms,进程之间通信也有开销，
                                // 	   适合用于大的项目
                                // 	**/
                                // 	loader:'thread-loader'
                                // },
                                {
                                    loader: 'babel-loader',
                                    options: {
                                        //预设：指示babel做怎样的兼容性处理
                                        presets: [
                                            ['@babel/preset-env', {
                                                //按需加载
                                                useBuiltIns: 'usage',
                                                //指定core-js版本
                                                corejs: {
                                                    version: 3
                                                },
                                                //指定兼容性做到哪个版本浏览器
                                                targets: {
                                                    chrome: '60',
                                                    ie: '10',
                                                    firefox: '60'
                                                }
                                            }
                                            ]
                                        ],
                                        //开启babel缓存，第二次构建时会读取之前的缓存
                                        cacheDirectory: true
                                    }
                                }
                            ]
                        },
                        {
                            test: /\.html$/,
                            loader: 'html-loader'
                        },
                        {
                            exclude: /\.(html|css|js|less|png|jpg|gif|json)$/i,
                            loader: 'file-loader',
                            options: {
                                outputPath: 'static',
                                name: '[hash:10].[ext]'
                            }
                        }
                    ]
                }
            ]
        },
        plugins: [
            new htmlwebpackplugin({
                template: './src/index.html',
                //压缩hml
                minify: {
                    //移除空格
                    collapseWhitespace: true,
                    //移除注释
                    removeComments: true
                }
            }),
            new MiniCssExtractPlugin({

                filename: 'css/build.[contenthash:10].css'
            }),
            new OpitimizeCssAssetsWebpackPlugin(),
            new WorkboxWebpackPlugin.GenerateSW({
                //帮助serviceWorker快速启动，替换旧的serviceWorker
                clientsClaim: true,
                skipWaiting: true
            }),
            //告诉webpack哪些库不需要打包
            new WebPack.DllReferencePlugin({
                context: __dirname,
                manifest: require(resolve(__dirname, 'dll/manifest.json'))
            }),
            // 把文件加入html
            new AddAssetHtmlPlugin({
                filepath: resolve(__dirname, 'dll/dllAxios.js'),
                publicPath: './'
            }),
            new BundleAnalyzerPlugin({
                analyzerMode: "server",
                analyzerHost: "127.0.0.1",
                analyzerPort: 8888, // 运行后的端口号
                reportFilename: "report.html",
                defaultSizes: "parsed",
                openAnalyzer: false,
                generateStatsFile: false,
                statsFilename: "stats.json",
                statsOptions: null,
                logLevel: "info"
            }),
            new CopyWebpackPlugin({
                patterns: [
                    {
                        from: resolve(__dirname, 'public'),
                        to: 'public'
                    }
                ]
            })
        ],
        mode: argv.mode,
        devServer: {
            port: 4000,
            contentBase: resolve(__dirname, 'build'),
            compress: true
        },
        devtool: 'source-map',
        optimization: {
            splitChunks: {
                chunks: "all"
            }
        },
        externals: {
            jsuery: 'jQuery'
        },
        resolve: {
            alias: {
                '@img': resolve(__dirname, 'src/img')
            },
            modules: [resolve(__dirname, 'node_modules'), 'node_modules']
        }
    }
}